"""
数据源相关的Pydantic模式
"""
from datetime import datetime
from typing import Dict, List, Optional, Any
from pydantic import BaseModel, Field, ConfigDict

from app.models.data_source import DataSourceType, DataSourceStatus, DataFormat


class DataSourceBase(BaseModel):
    """数据源基础模式"""
    name: str = Field(..., min_length=1, max_length=100, description="数据源名称")
    description: Optional[str] = Field(None, max_length=1000, description="数据源描述")
    source_type: DataSourceType = Field(..., description="数据源类型")
    data_format: DataFormat = Field(default=DataFormat.JSON, description="数据格式")
    connection_config: Dict[str, Any] = Field(default_factory=dict, description="连接配置")
    auth_config: Dict[str, Any] = Field(default_factory=dict, description="认证配置")
    data_schema: Dict[str, Any] = Field(default_factory=dict, description="数据模式")
    preprocessing_config: Dict[str, Any] = Field(default_factory=dict, description="预处理配置")
    validation_rules: List[Dict[str, Any]] = Field(default_factory=list, description="验证规则")
    sampling_config: Dict[str, Any] = Field(default_factory=dict, description="采样配置")
    is_active: bool = Field(default=True, description="是否活跃")


class DataSourceCreate(DataSourceBase):
    """数据源创建模式"""
    project_id: int = Field(..., description="项目ID")
    
    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "name": "温度传感器数据",
                "description": "智慧照明系统的温度传感器数据流",
                "source_type": "mqtt",
                "data_format": "json",
                "connection_config": {
                    "host": "mqtt.example.com",
                    "port": 1883,
                    "topic": "sensors/temperature"
                },
                "data_schema": {
                    "temperature": {"type": "float", "range": [-40, 85]},
                    "humidity": {"type": "float", "range": [0, 100]},
                    "timestamp": {"type": "datetime"}
                },
                "project_id": 1
            }
        }
    )


class DataSourceUpdate(BaseModel):
    """数据源更新模式"""
    name: Optional[str] = Field(None, min_length=1, max_length=100, description="数据源名称")
    description: Optional[str] = Field(None, max_length=1000, description="数据源描述")
    connection_config: Optional[Dict[str, Any]] = Field(None, description="连接配置")
    auth_config: Optional[Dict[str, Any]] = Field(None, description="认证配置")
    data_schema: Optional[Dict[str, Any]] = Field(None, description="数据模式")
    preprocessing_config: Optional[Dict[str, Any]] = Field(None, description="预处理配置")
    validation_rules: Optional[List[Dict[str, Any]]] = Field(None, description="验证规则")
    sampling_config: Optional[Dict[str, Any]] = Field(None, description="采样配置")
    is_active: Optional[bool] = Field(None, description="是否活跃")


class DataSourceInDB(DataSourceBase):
    """数据库中的数据源模式"""
    id: int
    status: DataSourceStatus
    project_id: int
    last_connected: Optional[datetime]
    last_data_received: Optional[datetime]
    error_message: Optional[str]
    total_records: int
    last_24h_records: int
    data_quality_score: int
    created_at: datetime
    updated_at: datetime
    
    model_config = ConfigDict(from_attributes=True)


class DataSource(DataSourceBase):
    """数据源响应模式"""
    id: int
    status: DataSourceStatus
    project_id: int
    last_connected: Optional[datetime]
    last_data_received: Optional[datetime]
    error_message: Optional[str]
    total_records: int
    last_24h_records: int
    data_quality_score: int
    created_at: datetime
    updated_at: datetime
    
    model_config = ConfigDict(from_attributes=True)


class DataSourceTest(BaseModel):
    """数据源测试模式"""
    connection_config: Dict[str, Any] = Field(..., description="连接配置")
    auth_config: Dict[str, Any] = Field(default_factory=dict, description="认证配置")
    source_type: DataSourceType = Field(..., description="数据源类型")
    timeout: int = Field(default=30, description="超时时间(秒)")


class DataSourceTestResult(BaseModel):
    """数据源测试结果模式"""
    success: bool = Field(..., description="测试是否成功")
    message: str = Field(..., description="测试结果消息")
    response_time: float = Field(..., description="响应时间(毫秒)")
    sample_data: Optional[Dict[str, Any]] = Field(None, description="样本数据")
    error_details: Optional[str] = Field(None, description="错误详情")


class DataSourceList(BaseModel):
    """数据源列表模式"""
    data_sources: List[DataSource]
    total: int
    page: int
    page_size: int


class DataSourceStats(BaseModel):
    """数据源统计模式"""
    total_data_sources: int
    active_data_sources: int
    inactive_data_sources: int
    error_data_sources: int
    total_records_today: int
    avg_data_quality_score: float
    data_sources_by_type: Dict[str, int]


class DataPreview(BaseModel):
    """数据预览模式"""
    sample_records: List[Dict[str, Any]] = Field(..., description="样本记录")
    total_records: int = Field(..., description="总记录数")
    schema_analysis: Dict[str, Any] = Field(..., description="模式分析")
    data_quality_report: Dict[str, Any] = Field(..., description="数据质量报告")
    timestamp_range: Dict[str, Any] = Field(..., description="时间范围")


class DataExport(BaseModel):
    """数据导出模式"""
    format: str = Field(..., description="导出格式")
    date_range: Optional[Dict[str, str]] = Field(None, description="日期范围")
    filters: Optional[Dict[str, Any]] = Field(None, description="过滤条件")
    include_metadata: bool = Field(default=True, description="包含元数据")